package com.lemontree.web.serviceImpl;

import com.lemontree.common.utils.LoggerUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lemontree.common.utils.StringUtil;
import com.lemontree.web.dao.UserMapper;
import com.lemontree.web.entity.User;
import com.lemontree.web.entity.UserExample;
import com.lemontree.web.service.UserService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created by YLBG-YCY-1325 on 2017/2/21.
 */
@Service("userService")
public class UserServiceImpl implements UserService{
    private static final Logger LOG = Logger.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Transactional
    public int insertUsers(User user) {
        if (null!=user){
            userMapper.insertSelective(user);
        }
        return 0;
    }

    public List<User> getUserByPhone(String phone) {
        if (StringUtil.isBlank(phone)){
            return null;
        }
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andPhoneEqualTo(phone);
        criteria.andDeleteTimeIsNull();
        return userMapper.selectByExample(userExample);
    }

    public User getUserByUserName(String userName) {
        if (StringUtil.isBlank(userName)){
            return null;
        }
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUserNameEqualTo(userName);
        criteria.andDeleteTimeIsNull();
        List<User> users = userMapper.selectByExample(userExample);
        if (CollectionUtils.isNotEmpty(users)){
            if (users.size()>1){
                LoggerUtils.error(getClass(),"脏用户-> phone ->"+users.get(0).getPhone());
            }
            return users.get(0);
        }
        return null;
    }

    public int updateUser(User user) {
        user.setUpdateTime(new Date());
        return userMapper.updateByPrimaryKey(user);
    }
}
